package com.hutu.kboshi.dao;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hutu.kboshi.common.constant.CommonConstant;
import com.hutu.kboshi.mapper.UserMapper;
import com.hutu.kboshi.pojo.dto.user.UserQueryRequest;
import com.hutu.kboshi.pojo.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

@Slf4j
@Repository
public class UserDao extends ServiceImpl<UserMapper, User> implements IService<User> {
    public User getUserByOpenId(String openId) {
        return lambdaQuery().eq(User::getOpenId, openId).one();
    }

    public long selectCount(String userAccount) {
        return lambdaQuery().eq(User::getUserAccount, userAccount).count();
    }

    public User getUserByAccountAndPassword(String userAccount, String encryptPassword) {
        return lambdaQuery()
                .eq(User::getUserAccount, userAccount)
                .eq(User::getUserPassword, encryptPassword)
                .one();
    }

    public Page<User> pages(UserQueryRequest userQueryRequest) {
        long current = userQueryRequest.getCurrent();
        long size = userQueryRequest.getPageSize();
        LambdaQueryWrapper<User> queryWrapper = getQueryWrapper(userQueryRequest);
        Page<User> page = new Page<>(current, size);
        return page(page, queryWrapper);
    }

    public LambdaQueryWrapper<User> getQueryWrapper(UserQueryRequest userQueryRequest) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        String userName = userQueryRequest.getUserName();
        String userProfile = userQueryRequest.getUserProfile();
        String userRole = userQueryRequest.getUserRole();
        Integer isUserVip = userQueryRequest.getIsUserVip();
        String userPermission = userQueryRequest.getUserPermission();
        String sortField = userQueryRequest.getSortField();
        String sortOrder = userQueryRequest.getSortOrder();
        queryWrapper.like(StringUtils.isNotBlank(userName), User::getUserName, userName)
                .like(StringUtils.isNotBlank(userProfile), User::getUserProfile, userProfile)
                .eq(StringUtils.isNotBlank(userPermission), User::getUserPermission, userPermission)
                .eq(StringUtils.isNotBlank(userRole), User::getUserRole, userRole)
                // TODO
//                .eq(isUserVip != null, User::g, isUserVip)
                .orderBy(StringUtils.isNotBlank(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),User::getCreateTime);
    return queryWrapper;
    }
}
